/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mytdev.commons.util;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 *
 * @author Yann D'Isanto
 */
public class RandomIterator<E> implements Iterator<E> {

    private List<E> data;
    private Random random;
    private Collection<E> underlyingCollection;
    private E lastReturnedElement = null;


    public RandomIterator(Collection<E> collection) {
        this.underlyingCollection = collection;
        this.data = new ArrayList<E>(underlyingCollection);
    }

    private synchronized Random getRandom() {
        if (random == null) {
            random = new Random();
        }
        return random;
    }

    @Override
    public boolean hasNext() {
        return data.size() > 0;
    }

    @Override
    public E next() {
        int index = getRandom().nextInt(data.size());
        lastReturnedElement = data.remove(index);
        return lastReturnedElement;
    }

    @Override
    public void remove() {
        underlyingCollection.remove(lastReturnedElement);
    }

    public static <E> RandomIterator<E> iterator(Collection<E> collection) {
        return new RandomIterator<E>(collection);
    }
}
